package com.distribute.framework.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.distribute.framework.core.web.helper.Utils;

public class Excel {
	
	List<List<Map<String,String>>> sheets = new ArrayList();
	List<List<List<String>>> arrays = new ArrayList();
	List<List<String>> headers = new ArrayList();
	
	public static Excel parse(File file){
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			return Excel.parse(is,file.getAbsolutePath());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	

	public static Excel parse(InputStream is,String filename){
		Excel excel = new Excel();
		
		//获得Workbook工作薄对象
    	Workbook workbook = null;
        try {
            if(filename.toLowerCase().endsWith(".xls")){
            	workbook = new HSSFWorkbook(is);
            }else if(filename.toLowerCase().endsWith(".xlsx")){
            	workbook = new XSSFWorkbook(is);
            }else{
            	workbook = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    	
    	//创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
    	if(workbook != null){
    		for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
    			//获得当前sheet工作表
        		Sheet sheet = workbook.getSheetAt(sheetNum);
        		List header = new ArrayList();
        		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        		List<List<String>> array = new ArrayList<List<String>>();
        		if(sheet == null){
        			continue;
        		}
        		//获得当前sheet的开始行
        		int firstRowNum  = sheet.getFirstRowNum();
        		//获得当前sheet的结束行
        		int lastRowNum = sheet.getLastRowNum();
        		Map<String,String> columnMapping = new LinkedHashMap();
        		//循环除了第一行的所有行
        		for(int rowNum = firstRowNum+0;rowNum <= lastRowNum;rowNum++){
        			//获得当前行
        			Row row = sheet.getRow(rowNum);
        			if(row == null){
        				continue;
        			}
        			//获得当前行的开始列
        			int firstCellNum = row.getFirstCellNum();
        			//获得当前行的列数
        			int lastCellNum = row.getPhysicalNumberOfCells();
        			Map<String,String> map = new LinkedHashMap();
        			List item = new ArrayList();
        			//循环当前行
        			for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
        				Cell cell = row.getCell(cellNum,MissingCellPolicy.RETURN_BLANK_AS_NULL);
        				if(cell==null)continue;
        				String letter = cell.getAddress().formatAsString().replaceAll("[\\d]+", "");
        				String value = getCellValue(cell);
                        if(rowNum==0){
                        	columnMapping.put(letter,value);
                        	header.add(value);
                        }else{
                        	map.put(columnMapping.get(letter), value);
                        	item.add(value);
                        }
        			}
        			if(rowNum==0){
                    	continue;
                    }
        			list.add(map);
        			array.add(item);        			
        		}
        		excel.addHeader(header);
        		excel.addSheet(list);
        		excel.addArray(array);
    		}
    		try {
				workbook.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    	}
		
		return excel;
	}
	
	public List<Map<String,String>> getSheet(int sheetIndex){
		return sheets.get(sheetIndex);
	}
	
	public List<List<Map<String,String>>> getSheets() {
		return sheets;
	}

	public void setSheets(List<List<Map<String,String>>> sheets) {
		this.sheets = sheets;
	}
	
	public void addSheet(List sheet) {
		this.sheets.add(sheet);
	}
	
	public List<List<String>> getArray(int sheetIndex){
		return arrays.get(sheetIndex);
	}
	
	public List<List<List<String>>> getArrays() {
		return arrays;
	}

	public void setArrays(List<List<List<String>>> arrays) {
		this.arrays = arrays;
	}
	
	public void addArray(List array) {
		this.arrays.add(array);
	}
	
	public List<String> getHeader(int sheetIndex){
		return headers.get(sheetIndex);
	}
	
	public List<List<String>> getHeaders() {
		return headers;
	}

	public void setHeaders(List<List<String>> headers) {
		this.headers = headers;
	}
	
	public void addHeader(List header) {
		this.headers.add(header);
	}
	
	public static String getCellValue(Cell cell){
		String cellValue = "";
		if(cell == null){
			return cellValue;
		}
		//把数字当成String来读，避免出现1读成1.0的情况
		if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
			cell.setCellType(Cell.CELL_TYPE_STRING);
		}
		//判断数据的类型
        switch (cell.getCellType()){
	        case Cell.CELL_TYPE_NUMERIC: //数字
	            cellValue = String.valueOf(cell.getNumericCellValue());
	            break;
	        case Cell.CELL_TYPE_STRING: //字符串
	            cellValue = String.valueOf(cell.getStringCellValue());
	            break;
	        case Cell.CELL_TYPE_BOOLEAN: //Boolean
	            cellValue = String.valueOf(cell.getBooleanCellValue());
	            break;
	        case Cell.CELL_TYPE_FORMULA: //公式
	            cellValue = String.valueOf(cell.getCellFormula());
	            break;
	        case Cell.CELL_TYPE_BLANK: //空值 
	            cellValue = "";
	            break;
	        case Cell.CELL_TYPE_ERROR: //故障
	            cellValue = "非法字符";
	            break;
	        default:
	            cellValue = "未知类型";
	            break;
        }
		return cellValue;
	}

	public static void main(String[] args) {
		System.setProperty("javax.xml.parsers.DocumentBuilderFactory",  
        "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");  
		Utils.trace(Excel.parse(new File("f://a.xls")).getSheets());
		Utils.trace(Excel.parse(new File("f://b.xlsx")).getArrays());
		Utils.trace(Excel.parse(new File("f://a.xls")).getHeaders());
	}

}